package com.blustreaksw.cyclecoach.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Button;

/***********************************************************************
 * Helper class to simply creation of DatePicker popup dialog.
 * 
 * @author Tomas Rivera
 *
 ***********************************************************************/
public class DatePickerFragment extends DialogFragment {
	private Calendar mCalendar;
	OnDateSetListener mDateSetListener;
	
	public DatePickerFragment() { }
	
	/********************************************************************************
	 * Configures dialog fragment that was created with default constructor.
	 * 
	 * @param	dateSetListener
	 * 		OnDateSetListener that handles when user clicks Ok.
	 * @param	calendar
	 * 		Calendar object that contains the default date to display
	 * 		when creating the dialog.
	 * @return	DatePickerFragment object
	 ********************************************************************************/
	public DatePickerFragment configureDatePicker(OnDateSetListener dateSetListener, Calendar calendar) {
		mDateSetListener = dateSetListener;
		mCalendar = calendar;
		return this;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the Calendar object date as the default date in the picker
		int year = mCalendar.get(Calendar.YEAR);
		int month = mCalendar.get(Calendar.MONTH);
		int day = mCalendar.get(Calendar.DAY_OF_MONTH);

		// Create a new instance of DatePickerDialog and return it
		DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), mDateSetListener, year, month, day);
		datePickerDialog.getDatePicker().setCalendarViewShown(false);
		return datePickerDialog;
	}
	
	/********************************************************************************
	 * Helper function that will change the text of the Button object passed to
	 * match the date value that was selected by the user in the Dialog. Note that
	 * the date String output is ENG/US format and is not aware of the user locale. 
	 * 
	 * @param	datePickerButton
	 * 		Button that the user would have clicked to display the dialog.
	 * @param	calendar
	 * 		Calendar object that holds the date that was selected by the user.
	 ********************************************************************************/
	public void updateDateButtonText(Button datePickerButton, Calendar calendar) {
		SimpleDateFormat f = new SimpleDateFormat("MMMM d, yyyy");
		String formattedDate = f.format(calendar.getTime());
		
		// TODO
		// Fix so that the String we create formats the date based
		// on the default Locale specified by the O/S.
		datePickerButton.setText(formattedDate);
	}
	
}
